use crate::ws::AppState;
use axum::extract::{ConnectInfo, State};
use axum::http::HeaderMap;
use axum::response::IntoResponse;
use axum::routing::post;
use axum::{Json, Router};
use std::net::SocketAddr;
use serde::{Deserialize, Serialize};
use void_log::log_info;
use crate::model::satori::{SatoriDirection, SatoriOrder};

/// # 消息结构
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SatoriMessageData {
    pub channel_id: String,    //频道 ID
    // 消息增删改查
    pub message_id: Option<String>,    //消息 ID
    pub content: Option<String>,    //消息内容
    // 获取消息列表
    pub next: Option<String>,    //分页令牌
    pub direction: Option<SatoriDirection>,    //查询方向
    pub limit: Option<i64>,    //消息数量限制
    pub order: Option<SatoriOrder>,    //对结果排序
}

async fn message_create(State(app_state): State<AppState>,
                        headers: HeaderMap, ConnectInfo(addr): ConnectInfo<SocketAddr>,
                        Json(data): Json<SatoriMessageData>) -> impl IntoResponse {
    log_info!("Connection address {}", &addr.to_string());
    if let Some(authorization) = headers.get("authorization") {
        let user_token = authorization.to_str().unwrap().trim_start_matches("Bearer ");
        app_state.message_create(data, user_token).await
    }
}

pub async fn router(app: Router<AppState>) -> Router<AppState> {
    app.route("/message.create", post(message_create))
}